--  NewTeamApplyController

local NewTeamApplyView = import("..views.NewTeamApplyView")

local fileName = string.getModeName(...)
local ClassRef = class(fileName, app.mvc.ControllerBase)

function ClassRef:ctor(params)
	self.super.ctor(self, params)
end

function ClassRef:init()
	self._model = app:getInst("TeamModel")

	self._curPanelSelectedIdx = 1 -- 右侧panel选中索引、默认为邀请
	self._applySelectedIdx =  1 -- 邀请panel选中索引、默认为好友

	self._partnerChangedHandler = UD:onChanged("partner", function()
		if 1 == self._curPanelSelectedIdx and 5 == self._applySelectedIdx then
			self:refreshListView()
		end
	end)
end

function ClassRef:removeListeners()
	UD:unChanged("partner", self._partnerChangedHandler)
end

function ClassRef:listEvent()
    return {
    	"onTeamSettingUpdate",
    	"onTeamNewApplyer",
		"onTeamMemberUpdate",
		ViewEvent.Partner_EmployPartnerFail
	}
end


function ClassRef:onEvent(eventName, data)
	if eventName == "onTeamSettingUpdate" then
		if not self:isViewAlive() then return end
		self._view:refreshAutoApprove( self._model:isAutoApprove(), self._model:isInCrossMatch() )
	elseif eventName == "onTeamNewApplyer" then
		if not self:isViewAlive() then return end
		if self._model:isMyTeam() then
			self._model:reqGetApplicationList()
		end
	elseif eventName == "onTeamMemberUpdate" then
		self:refreshListView()
	elseif eventName == ViewEvent.Partner_EmployPartnerFail then
		self:refreshListView()
	end
end

function ClassRef:openView(data)
	if DungeonManager:isCrossDungeon() then
		-- 跨服副本不需要拉取队伍信息
		display.pushToast(L("CrossServerTips2"))
		return
	end

	local idx
	if data[1] then -- 指定一级菜单选中项
		idx = data[1]
	end
	if not idx then
		idx = 1 -- 默认第一个标签页、即邀请页签
	end

	local isMyTeam = self._model:isMyTeam()
	-- 第二个标签而且自己不是队长，强制切换到第一个标签
	if idx == 2 and not isMyTeam then
		display.pushToast( L("lua_code_text_498") )
		idx = 1
	end
	if isMyTeam then
		self._model:reqGetApplicationList()
	end

	if cc.isDead(self._view) then
		self._view = NewTeamApplyView.new( app.mvc.VIEWTYPE_BLUR, self._model:isMyTeam())
		self._view:onCloseView(handler(self, self.closeView))
		self._view:onClearView(handler(self, self.clearView))
		self._view:onOperate(handler(self, self.onOperate))
	end
	self:addChild(self._view)

	local function call()
		self._view:show( idx )

		if data[2] then -- 指定二级菜单选中项
			if not data[1] or 1 ~= data[1] then -- data[1]不存在 || 不是指向邀请panel
				print( " ------->>> NewTeamApplyController:openView 指定二级菜单时候指定的一级菜单不是邀请?" .. tostring( data[1] ) .. " ; " .. tostring( data[2] ) )
				return
			else
				assert( 1 ==  data[1], " -------->>>>> NewTeamApplyController:openView " .. tostring( data[1] ) .. " ; " .. tostring( data[2] ) )
				self._view:getRightPanelByIndex( data[1] ):setSelectedTag( data[2] )
			end
		end

		self._autoApproveTemp = self._model:isAutoApprove() -- "自动同意申请" 状态
		if 2 == idx then -- 展开的是申请UI、则需要刷新"自动申请"按钮状态
			self._view:refreshAutoApprove( self._autoApproveTemp, self._model:isInCrossMatch() )
		end
	end


	local firendModel = app:getInst("FriendModel")
	-- 如果有好友，拉取最新的好友状态
	local friends = firendModel:getFriends()
	if #friends > 0 then
		self._view:hide()
		firendModel:reqFriendsStatus(function ()
			call()
		end)
	else
		call()
	end


end
function ClassRef:closeView(data)
	if self._view then
		self:removeChild(self._view, {isFade=false})

		-- 正常关闭UI的时候才会向服务器同步 "自动同意申请" 状态
		local temp = self._model:getTeamSettingClone()
		if temp.autoApprove ~= self._autoApproveTemp then
			temp.autoApprove = self._autoApproveTemp
			self._model:C2S_UpdateRecruitInfo( temp )
		end

		self._view = nil
		self._curPanelSelectedIdx = 1
		self._applySelectedIdx = 1
	end
end
function ClassRef:clearView(data)
	if self._view then self._view = nil end
	app:sendMsg("FriendModel", "clearRecents")
end

-- 邀请进队处理
function ClassRef:_invitedToTeam(data)
	if not self:isViewAlive() then return end

	local teamSetting = self._model:getTeamSetting()

	local metadata = data["applicant"]
	if not metadata then
		metadata = data["info"]
	end
	if not metadata then
		metadata = data
	end
	local classId = metadata["classID"] or metadata["classId"]
	local level = metadata["lv"] or metadata["level"]
	local specialistId = metadata["specialistID"]

	if self._model:isMyTeam() then
		self._model:reqInviteToTeam( data.uid, data.level )
	else
		if (teamSetting.isLvLocateBetweenMinMaxLv and not teamSetting:isLvLocateBetweenMinMaxLv( level )) or (teamSetting.isClassIdNeeded and not teamSetting:isClassIdNeeded( specialistId ) ) then
			self._view:playTipsAnimation()
		else
			self._model:reqInviteToTeam( data.uid, data.level )
		end
	end
end

-- 回复入队申请
function ClassRef:_replyApplication(uid, isAgree)
	if not self:isMyTeamLeader() then 
		display.pushToast( L("lua_code_text_522") )
		return
	end

	local team = self._model:getTeam()
	if isAgree and team:isInCrossMatch() then
		-- 跨服副本添加弹框提示
		local dlg = display.newConfirmDialog(L("CrossServerTips3"),
		        function() -- 确定
		            self._model:reqReplyApplication(uid, isAgree)
		        end)
		UIHandler:addPopDialog( dlg )
	else
		self._model:reqReplyApplication(uid, isAgree)
	end
end

function ClassRef:onOperate( op, ... )
	-- print("NewTeamApplyController.onOperate op", op)
	-- dump({...}, "NewTeamApplyController.onOperate data")
	local data = ...

	if op == "TeamApply_switchpanel" then
		self._curPanelSelectedIdx = data
		self:refreshListView()
	elseif op == "NewApplyListPanel_changeAutoApprove" then -- 申请panel改变"自动同意"状态
		if self:isMyTeamLeader() then
			self._autoApproveTemp = data
		else
			display.pushToast( L("lua_code_text_522") )
		end
	elseif op == "NewApplyListRender_Observe" then -- 观察
		EM:notify("onWatchUI", data)
	elseif op == "NewApplyListRender_Refuse" or op == "NewApplyListRender_Agree" then -- 同意/拒绝了某人的申请
		self:_replyApplication(data[1], data[2])
	elseif op == "NewApplyListRender_Whisper"  then -- 私聊
		app:sendMsg("IMRoomController", "speakToTarget", data)
	elseif op == "NewApplyListRender_InviteToTeam"  then -- 邀请进队
		self:_invitedToTeam( data )
	elseif op == "NewApplyListRender_ChangePartnerStatus"  then -- 切换随从的雇佣状态
		local partnerDataTemp = data._partnerData
		if not partnerDataTemp then
			print( " ---------->>>> 没有随从数据，NewApplyListRender_ChangePartnerStatus" )
			return
		end
		if self:isMyTeamLeader() then
			UD.partnersData:C2S_EmployPartner(partnerDataTemp:getId())
		else
			data:setpartnerBtnStatus( not data:getpartnerBtnStatus() )
			display.pushToast( L("lua_code_text_522") )
		end
	elseif op == "InvitePanel_changeTag" then -- 邀请panel切换tag
		assert( 1 == self._curPanelSelectedIdx, " ---------->>>>>> 非邀请panel时企图切换tag " )
		if self._applySelectedIdx ~= data then
			self._applySelectedIdx = data
			self:refreshListView()
		end
	end
end

-- 判断操作发起人是否是队长
function ClassRef:isMyTeamLeader()
	return self._model:isMyTeam()
end
------------------------------ view logic ---------------------------------
-- 其他地方调用：刷新申请者列表
function ClassRef:updateApplyList()
	if 2 == self._curPanelSelectedIdx then
		self:refreshListView()
	end
end

-- 其他地方调用：刷新 邀请-近期 列表
function ClassRef:updateRecentInvitList()
	if 1 == self._curPanelSelectedIdx and 4 == self._applySelectedIdx then
		self:refreshListView()
	end
end

function ClassRef:refreshListView()
	if not self:isViewAlive() then return end

	local panelTemp = self._view:getRightPanelByIndex( self._curPanelSelectedIdx )
	local listView = panelTemp:getListView()

	-- 刷新列表
	local function refreshList( dataTemp )
		if cc.isDead(listView) then
			return
		end
		listView:stopAllActions()
		local len = #dataTemp
		local curIdx = 0
		local function addApplyList()
			curIdx = curIdx + 1
			if curIdx <= len then
				local render = listView:createRender(curIdx)
				if 1 == self._curPanelSelectedIdx then -- 邀请?
					if 5 == self._applySelectedIdx then -- 随从？
						render:setShowMode( 3 )
						render:setPartnerData( dataTemp[curIdx] )
					else
						render:setShowMode( 2 )
						render:setData( dataTemp[curIdx] )
					end
				else
					render:setShowMode( 1 )
					render:setData( dataTemp[curIdx] )
				end
				render:onBtnClick(handler(self, self.onOperate))
			else
				--删掉多余的item
				display.removeListUnuseItem(listView, #dataTemp)
				listView:stopAllActions()
			end
		end
		listView:schedule(addApplyList, 0)
	end


	local dataTemp = {}
	if 1 == self._curPanelSelectedIdx then -- 邀请
		if 1 == self._applySelectedIdx then -- 好友
			dataTemp = app:sendMsg("FriendModel", "getOnlineFriends")
		elseif 2 == self._applySelectedIdx then -- 工会成员
			if UD:isInGuild() then -- 在公会中？
				local function getGuildMmeberCB( guildMemberList )
					local temp = {}
					if guildMemberList and #guildMemberList > 0 then
						for i, member in ipairs( guildMemberList ) do
							if member:isOnline() and not member:isMe() and not self._model:isInTeam( member:getMemberId() ) then
								table.insert(temp, member:getMemberInfo())
							end
						end
					end
					dataTemp = temp
					refreshList( dataTemp )
				end
				local newGuildModelTemp = app:getInst( "NewguildModel" )
				newGuildModelTemp:reqGuildMemberList( newGuildModelTemp:getGuildId(), getGuildMmeberCB )
			end
		elseif 3 == self._applySelectedIdx then -- 附近玩家
			local nearbyUsers = FieldManager:getNearbyUserNotInTeam()
			nearbyUsers = nearbyUsers and nearbyUsers or {}
			for _, v in pairs(nearbyUsers) do
				if not self._model:isInTeam( v.uid ) then
					dataTemp[#dataTemp + 1] = v
				end
			end
		elseif 4 == self._applySelectedIdx then -- 近期组过队伍的其他玩家
			local recents = app:sendMsg("FriendModel", "getRecents")
			for i,v in ipairs(recents) do
				if v.online and not self._model:isInTeam( v.info.uid ) then
					dataTemp[#dataTemp + 1] = v
				end
			end
		elseif 5 == self._applySelectedIdx then -- 已经激活的佣兵
			local partners = UD.partnersData:getAlreadyHavePartners(true)
			dataTemp = partners
		else
			print( " ----------->>>>> 企图邀请未知类型成员 " )
		end
	elseif 2 == self._curPanelSelectedIdx then -- 申请
		dataTemp = self._model:getApplicantList()

		self._view:refreshAutoApprove( self._model:isAutoApprove(), self._model:isInCrossMatch() )
	end
	refreshList( dataTemp )
end

return ClassRef
